<template>
  <a-card :bordered="false">
    <h3>话题列表</h3>
    <ContentFilter
      ref="filter"
      :type="3"
      :url="url"
      :extensionBrandList="brandList"
      :extensionVisible.sync="extensionVisible"
      @onSearch="onSearch"></ContentFilter>
    <a-tabs v-model="activeKey" @change="tabChange">
      <a-tab-pane v-for="item in tabList" :tab="item.name" :key="item.status">
      </a-tab-pane>
    </a-tabs>
    <s-table
      ref="table"
      size="default"
      :rowKey="record => record.id"
      :columns="columns"
      :data="loadData"
      :pagination="paginationProps"
      :scroll="{ x: 1300 }"
    >
      <span slot="customNum">参与人数/阅读数/讨论数 <a-tooltip>
        <template slot="title">
          参与人数：发布关联该话题内容的用户数
          阅读数：关联话题的内容阅读数之和
          讨论数：关联话题的内容下评论数之和
        </template>
        <a-icon type="question-circle" />
      </a-tooltip></span>
       <span slot="image" slot-scope="text, record, index">
        <img class="img" @click="handleShowImg(0, [record.topicImage])"  :src="record.topicImage" alt="">
      </span>
      <span slot="topicIntroduction" slot-scope="record">
        <a-popover :overlayStyle="{ width: '380px', height: 'auto' }">
          <template slot="content">
            <p style="word-break: break-all;">{{ record.topicIntroduction }}</p>
          </template>
          <span class="remarks">{{ record.topicIntroduction }}</span>
        </a-popover>
      </span>
      <span slot="topicType" slot-scope="record">
        <span v-if="record.topicType == 0">普通话题</span>
        <span v-if="record.topicType == 1">有奖话题</span>
      </span>
      <span slot="customNum" slot-scope="record">
        {{record.peopleNumber}}/{{record.browseNumber}}/{{record.commentsNumber}}
      </span>
      <span slot="topicProgram" slot-scope="record">
        <a-tooltip>
          <template slot="title">
            {{record.topicProgram}}
          </template>
          <template  v-if="record.topicProgram">{{record.topicProgram.split(',').slice(0,3).join('、')}}</template>
          <div style="color: #999;" v-if="record.topicProgram">共{{record.topicProgram.split(',').length}}个小程序 ></div>
          <div style="color: #999;" v-else>/</div>
        </a-tooltip>
      </span>
      <span slot="time" slot-scope="record">
        <p>{{record.startTime}}</p>
        <p>{{record.endTime}}</p>
      </span>
      <span slot="action" slot-scope="record">
        <template v-if="activeKey == 1 || activeKey == 2">
          <a @click="handleShowExtension(record)">推广</a>
          <a-divider type="vertical" />
        </template>
        <template v-if="activeKey == 1 || activeKey == 3">
          <a @click="topicContentList(record.id)">话题内容</a>
          <a-divider type="vertical" v-if="(activeKey == 3 && record.topicType == 1) || activeKey != 3" />
        </template>
        <template v-if="activeKey == 2">
          <a-popconfirm
            title="确定要发布该话题吗？"
            ok-text="确定"
            cancel-text="暂不"
            @confirm="handleOnline(record.id)"
          >
            <a>上线</a>
          </a-popconfirm>
          <a-divider type="vertical" />
        </template>
        <template v-if="activeKey == 1 || activeKey == 2">
          <a @click="handleEdit(record.id)">编辑</a>
          <a-divider type="vertical" />
        </template>
        <template v-if="activeKey == 1">
          <a-popconfirm
            title="确定要下线该内容吗？"
            ok-text="确定"
            cancel-text="暂不"
            @confirm="handleOffline(record.id)"
          >
            <a>下线</a>
          </a-popconfirm>
        </template>
        <template v-if="activeKey == 2">
          <a-popconfirm
            title="确定要删除该话题吗？"
            ok-text="确定"
            cancel-text="暂不"
            @confirm="handleDelet(record.id)"
          >
            <a>删除</a>
          </a-popconfirm>
        </template>
        <a v-if="activeKey == 3 && record.topicType == 1" @click="winningList(record.id)">中奖名单</a>
      </span>
    </s-table>
    <ParagraphPic :current="imgCurrent" :visible.sync="imgVisible" :imgs="imgs"></ParagraphPic>
  </a-card>
</template>
<script>
  import { topicPage, topicAddOrUpdate, topicDelete, topicNoStart, contentOnline} from '@/api/micromall/communityContent'
  import { STable } from '@/views/box/components'
  import ContentFilter from '../../components/ContentFilter'
  import ParagraphPic from '../../components/ParagraphPic'
  import { ongoingColumns, notStartedColumns, endedColumns } from '../contentManagement/topicList.js'
  import { brandList } from '../../components/brandList.js'
  const tabList = [
  {
    name: '进行中',
    status: '1'
  },
  {
    name: '未开始',
    status: '2'
  },
  {
    name: '已结束',
    status: '3'
  }
]
  export default {
    components: {
      ContentFilter,
      STable,
      ParagraphPic
    },
    data() {
      return {
        brandList: [],
        url: '',
        extensionVisible: false,
        imgCurrent: 0,
        imgVisible: false,
        imgs: [],
        tabList,
        activeKey: tabList[0].status,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        columns: ongoingColumns,
        paginationProps: {
          total: 0,
          showTotal: total => `共有 ${total} 条数据`
          // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
        },
        queryParam: {},

        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          if (this.requestFlag()) return
          const data = {
            ...this.queryParam,
            current: parameter.pageNo,
            size: parameter.pageSize,
            options: this.activeKey
          }
          return topicPage(data).then(res => {
            if (res.code === 200) {
              const { records, total, size, current } = res.data
              const data = {
                page: {
                  count: total,
                  pageNo: current,
                  pageSize: size,
                  pages: Math.ceil(total / size)
                },
                data: records
              }
              return data
            } else {
              this.$message.error(res.msg)
              const data = {
                page: {
                  count: 0,
                  pageNo: 0,
                  pages: 0
                },
                data: []
              }
              return data
            }
          })
        }
      }
    },
    created() {
    },
    activated() {
      this.getCount()
    },
    computed: {},
    mounted() {
    },
    watch: {
      $route(to, from) {
        const whiteList = [
          '/micromall/community/contentManagement/addOrEditOfficialTopic/',
          '/micromall/community/contentManagement/winningList/'
        ]
        const currentPathBase = '/micromall/community/contentManagement/topicList'
        const currentPath = this.$route.path
        if (this.checkRoute(from.path, whiteList) && to.path.includes(currentPathBase)) {
          this.$refs.table.refresh() // 刷新当前列表（记录上次页码）
        } else {
          if (currentPath.includes(currentPathBase) ) {
            this.activeKey = tabList[0].status
            this.tabChange(this.activeKey) // 刷新当前页面
          }
        }
      }
    },
    methods: {
      requestFlag() {
        const currentPathBase = '/micromall/community/contentManagement/topicList'
        const currentPath = this.$route.path
        if (!currentPath.includes(currentPathBase)) return true
        return false
      },

      handleShowExtension(record) {
        const { id, topicProgramId }  = record
        const filterTopicProgramId = topicProgramId.split(',')
        this.brandList = brandList.filter(e => filterTopicProgramId.includes(e.weid))
        this.extensionVisible = true
        this.url = `/packages/wm-cloud-jnbycommunity/topicDetail/index?id=${id}`
      },

      // 获取状态数量
      getCount() {
        if (this.requestFlag()) return
        topicNoStart().then(res => {
          if (res.code === 200) {
            this.tabList[1].name = `未开始（${res.data || 0}）`
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      // 上线
      handleOnline(id) {
        const data = {
          id,
          status: '1',
          startTime: this.getTime()
        }
        contentOnline(data).then(res => {
          if (res.code === 200) {
            this.$refs.table.refresh()
            this.getCount()
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      // 下线
      handleOffline(id) {
        const data = {
          id,
          status: '3',
          endTime: this.getTime()
        }
        console.log(contentOnline, 'contentOnline')
        contentOnline(data).then(res => {
          if (res.code === 200) {
            this.$refs.table.refresh()
            this.getCount()
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      // 获取当前时间
    getTime() {
      const nowdate = new Date()
      const year = nowdate.getFullYear(),
        month = this.checkTime(nowdate.getMonth() + 1),
        date =  this.checkTime(nowdate.getDate()),
        h =  this.checkTime(nowdate.getHours()),
        m = this.checkTime(nowdate.getMinutes()),
        s =  this.checkTime(nowdate.getSeconds())
      return `${year}-${month}-${date} ${h}:${m}:${s}`
    },

    // 时间补位
    checkTime(i) {
      if (i < 10) {
        i = '0' + i
      }
      return i
    },

      // 删除
      handleDelet(id) {
        topicDelete({id}).then(res => {
          if (res.code === 200) {
            this.$refs.table.refresh()
            this.getCount()
          } else {
            this.$message.error(res.msg || res.message)
          }
        })
      },

      tabChange(activeKey) {
        this.$nextTick(() => {
          this.activeKey = activeKey
          switch(activeKey) {
              case '1':
                // 进行中
              this.columns = ongoingColumns
                  break;
              case '2':
                // 未开始
              this.columns = notStartedColumns
                  break;
              case '3':
                // 已结束
              this.columns = endedColumns
                  break;
          } 
          this.$refs.filter.reset()
        })
      },

       // 中奖名单
      winningList(id) {
        this.$router.push(`/micromall/community/contentManagement/winningList/${id}`)
      },

      // 话题内容
      topicContentList(id) {
        this.$router.push(`/micromall/community/contentManagement/topicContentList/${id}`)
      },

      checkRoute(fromPath, routeArr) {
        for (let i = 0; i < routeArr.length; i++) {
          if (fromPath.includes(routeArr[i])) {
            return true
          }
        }
        return false
      },

      // 编辑
      handleEdit(id) {
        this.$router.push(`/micromall/community/contentManagement/addOrEditOfficialTopic/${id}`)
      },

      // 详情
      handleDetails(lookId, state) {
        this.$router.push(`/micromall/community/contentManagement/details/1`)
      },

      // 查看大图
      handleShowImg(index, productImgList){
        this.imgCurrent = index
        this.imgVisible = true
        this.imgs= productImgList
     },

      //查询
      onSearch(obj) {
        this.queryParam = obj
        this.$refs.table.refresh(true)
      }
    }
  }
</script>
<style lang="less" scoped>
  /deep/ .ant-tabs-bar {
    margin-bottom: 0;
  }

  .img-wrapper {
    display: flex;

    .img-list {
      display: flex;
    }

    .img-text {
      line-height: 60px;
      color: #999;
    }
  }

  .img {
    display: block;
    margin: 0 auto;
    width: 60px;
    height: 60px;
    border: 1px dashed #f5f5f5;
    object-fit: scale-down;
    cursor: pointer;
  }

  .remarks {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    word-break: break-all; /* 追加这一行代码 */
    /* autoprefixer: off */
    -webkit-box-orient: vertical;
    /* autoprefixer: on */
    // text-align: left;
  }
  .product {
    display: flex;
    overflow: hidden;
    .img{
      margin: 0;
    }
    .product-name{
      flex: 1;
      margin-left: 5px;
      width: 80px;
      text-align: left;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      word-break: break-all; /* 追加这一行代码 */
      /* autoprefixer: off */
      -webkit-box-orient: vertical;
      /* autoprefixer: on */
    }
  }
  .product-list {
    .product-item {
      line-height: 18px;
      text-align: left;
    }

    .product-num {
      cursor: pointer;
      text-align: left;
    }
  }
  .content-record{
    position: absolute;
    right: 0;
    top: 15px;
  }
  .image-video-wrapper{
    position: relative;
    width: 60px;
    height: 60px;
    margin: 0 auto;
    .img-num{
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      line-height: 18px;
      text-align: center;
      font-size: 12px;
      color:#fff;
      background: rgba(0, 0, 0, 0.5);
    }
  }
</style>
